package com.lxw.service;


import com.lxw.framework.domain.cms.CmsPage;
import com.lxw.framework.exception.CustomException;
import com.lxw.framework.model.response.CommonCode;
import com.lxw.dao.CmsPageDao;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

@Service
@Slf4j
public class CmsPageServiceImpl implements ICmsPageService {
    @Autowired
    CmsPageDao cmsPageDao;
    @Autowired
    GridFsTemplate gridFsTemplate;
    @Autowired
    GridFSBucket gridFSBucket;

    @Override
    public void writeFile(String pageId) {
// 把前面业务保存的静态化HTML文件写入磁盘  1读取文件  2.磁盘物理路径 3.写入
        Optional<CmsPage> byId = cmsPageDao.findById(pageId);
        if(!byId.isPresent()){
            throw new CustomException(CommonCode.FAIL);
        }
        CmsPage cmsPage = byId.get();

        // 1.读取文件
        String fileId = cmsPage.getHtmlFileId();
        try {
            // 1.1h获取集合
            GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
            log.info("【{}】",gridFSFile);
            // 1.2. 获取文件块
            GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());

            // 1.3.获取文件合并流
            GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
            // 1.4.获取输入流
            InputStream inputStream = gridFsResource.getInputStream();


            // 2.磁盘物理路径  站点物理路径+页面物理路径+访问地址+页面名称(站点物理路径不再处理)
            String filePath = cmsPage.getPagePhysicalPath()+cmsPage.getPageWebPath()+cmsPage.getPageName();


            // 3. 写入磁盘
            IOUtils.copy(inputStream,new FileOutputStream(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }



    }
}
